package org.tju.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.tju.mapper.UserMapper;
import org.tju.po.User;

import org.tju.service.UserService;
import org.tju.util.CommonUtil;
import org.tju.util.TokenUtil;

import java.util.Map;


@Service
public class UserServiceImpl implements UserService {

	 @Autowired
	    private UserMapper userMapper;
	 
	    @Override
	    public User getUserByIdByPass(User user) {
			int result=checkMember(user);
			if(result==0) {
				userMapper.quitMember(user);
			}//输入不存在账号，返回空
			if(result ==-1) {
				return null;
			}
			User user2 =userMapper.getUserByIdByPass(user);
			if(user2!=null) {//密码没有输错
				Map<String,Object> token = TokenUtil.sign(user2);
				user2.setToken(token);
			}
			return user2;
	    }
	    
	    @Override
	    public int getUserById(String userId) {
	        return userMapper.getUserById(userId);
	    }
	    
	    @Override
	    public int saveUser(User user) {
	        return userMapper.saveUser(user);
	    }

	@Override
	public User updateUser(User user) {
		int result = userMapper.updateUser(user);
		if (result != 0) {
			User getUser = userMapper.getDetailedUserById(user);
			return getUser;
		} else {
			User getUser = null;
			return getUser;
		}
	}

	@Override
	public User getMember(User user) {
		User user2 = userMapper.getDetailedUserById(user);
		int time = checkMember(user);
		if(time==0) {//不是会员，设置时间和开通日期
			String curDate = CommonUtil.getCurrentDate();
			user.setStartDate(curDate);
			user.setMember(1);
			userMapper.addMember(user);
		}else {//本来为会员，只增加时间即可
			user.setPeriod(user.getPeriod()+time);
			user.setStartDate(user2.getStartDate());
			userMapper.addMember(user);
		}
		return userMapper.getDetailedUserById(user);
	}

	//检查是否为会员
	@Override
	public int checkMember(User user) {
		User user2 = userMapper.getDetailedUserById(user);
		//不存在则会报空指针异常
		if(user2!=null) {
			if (user2.getMember() == 0)
				return 0;
			else {
				String curDate = CommonUtil.getCurrentDate();
				int check = CommonUtil.checkDate(curDate, user2.getStartDate(), user2.getPeriod());
				if (check == 0) {
					userMapper.quitMember(user);
					return 0;
				}
				else {
					return user2.getPeriod();
				}
			}
		}
		return -1;
	}

}
